package model

import (
	"time"
	"errors"
)

type Question struct {
	Id         int64
	Type       int32
	CreatedAt  time.Time `xorm:"created"`
	UpdatedAt  time.Time `xorm:"updated"`
	Stem       string    `xorm:"text"`
	Pic        string
	Answer     string    `xorm:"text"`
	Explain    string    `xorm:"text"`
	ExpPic     string
	Selections map[string]string
}

func (q *Question) Some(ids []int64) ([]Question, error) {
	var question []Question
	err := orm.In("id", ids).Find(&question)
	return question, err
}

func (q *Question) OneById() error {
	ok, err := orm.ID(q.Id).Get(q)
	if !ok {
		return errors.New(QuestionNotFound)
	}
	return err
}

func (q *Question) StemLike(like string) ([]Question, error) {
	var questions []Question
	err := orm.Where("stem LIKE ?", "%"+like+"%").Find(&questions)
	return questions, err
}

func (q *Question) UpdateBy(col ...string) error {
	ok, err := orm.ID(q.Id).Cols(col...).Update(q)
	if ok == 0 {
		return errors.New(QuestionUpdateFailed)
	}
	return err
}

func (q *Question) Create() error {
	ok, err := orm.Insert(q)
	if ok == 0 {
		return errors.New(QuestionCreateFailed)
	}
	return err
}
